import { PetModel } from "../model/PetModel";
import { EnumBagItemGrid, ItemModuleData, ItemModuleS } from "./ItemModule";

export class PetModuleC extends ModuleC<PetModuleS, null> {
    
}

export class PetModuleS extends ModuleS<PetModuleC, null> {
    private petModelMapping: Map<number, PetModel> = new Map()

    protected onStart(): void {
        let itemMD = ModuleService.getModule(ItemModuleS)
        itemMD.onPlayerAppearanceChanged.add(this.refreshPlayerPet, this)
    }

    protected onPlayerEnterGame(player: Player): void {
        if (this.petModelMapping.has(player.playerId)) return
        Script.spawnScript(PetModel).then(model=>{
            model.ownerPlayerID = player.playerId
            this.petModelMapping.set(player.playerId, model)
            this.refreshPlayerPet(player.playerId)
        })
    }
    
    protected onPlayerLeft(player: Player): void {
        if (this.petModelMapping.has(player.playerId)) {
            let model = this.petModelMapping.get(player.playerId)
            model.destroy()
            this.petModelMapping.delete(player.playerId)
        }
    }

    private refreshPlayerPet(playerID:number){
        let petModel = this.petModelMapping.get(playerID)
        if(!petModel) return

        let itemData = DataCenterS.getData(playerID, ItemModuleData)
        let arrayIndex = 0
        for(let grid = EnumBagItemGrid.petStart;grid <= EnumBagItemGrid.petEnd;grid++){
            let petVo = itemData.getItemByGrid(grid)
            if(!petVo){
                petModel.resetPetByIndex(arrayIndex)
            }else{
                petModel.setPetByIndex(arrayIndex, petVo.baseInfo.cfgID)
            }
            arrayIndex++
        }
    }

    net_test(){
        let randomIndex = Math.round(Math.random() * PetModel.MaxPetCount)
        let model = this.petModelMapping.get(this.currentPlayerId)
        let petIDs = [101,102,103,104,105]
        if(Math.random() > 0.8){
            model.resetPetByIndex(randomIndex)
        }
        else{
            model.setPetByIndex(randomIndex, petIDs[Math.floor(Math.random() * petIDs.length)])
        }
    }
}